using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class WarehouseItem : MonoBehaviour
{
    public Text m_TitleL;
    public WarehouseItemsItem m_WarehouseItemItemPrefab;
    public GameObject m_WarehouseContent;
    List<WarehouseItemsItem> m_Items = new List<WarehouseItemsItem>();
    WarehouseItem m_ItemPreview;
    Warehouse m_Warehouse;
    private void Awake()
    {
    }
    void Start()
    {
        
    }

    void Update()
    {
        
    }
    public void OnWarehouseAddItem(int typeID, int number)
    {
        foreach(var i in m_Items)
        {
            if(i.m_Item.typeID == typeID)
            {
                //i.m_Item.number += number;
                i.Init(i.m_Item);
                return;
            }
        }
        var newItem = ItemManager.Instance.FindItem(typeID);
        newItem.number = number;
        AddItem(newItem);
    }
    public void Init(Warehouse warehouse) 
    {
        m_Warehouse = warehouse;
        foreach (var i in warehouse.items)
        {
            AddItem(i.Value);
        }
        m_TitleL.text = m_Warehouse.name;
    }
    public void AddItem(Item item)
    {
        var warehouseItem = Instantiate(m_WarehouseItemItemPrefab);
        warehouseItem.Init(item);
        warehouseItem.transform.SetParent(m_WarehouseContent.transform);
        warehouseItem.transform.SetSiblingIndex(m_WarehouseContent.transform.childCount);
        warehouseItem.m_WarehousePanel = this;
        m_Items.Add(warehouseItem);
    }
    public void RemoveItem(WarehouseItemsItem item)
    {
        m_Warehouse.RemoveItem(item.m_Item.typeID, 1);
        if (m_Warehouse.GetItem(item.m_Item.typeID) == null)
        {
            m_Items.Remove(item);
            Destroy(item.gameObject, 0.1f);
        }
    }
    public void OnDrop(BaseEventData eventData)
    {
        if (eventData.selectedObject == null)
            return;
        var itemDrager = eventData.selectedObject.GetComponent<ItemDrager>();
        if (itemDrager == null)
            return;
        var item = itemDrager.m_Item;
        if (item == null)
            return;
        m_Warehouse.AddItem(item.typeID, 1);
        foreach (var i in m_Items)
        {
            if(i.m_Item.typeID == item.typeID)
            {
                MessageShow.Instance.Messaage("Move the item back to the ship's warehouse");
                Destroy(itemDrager.gameObject);
                eventData.selectedObject = null;
                return;
            }
        }
    }
}

